package org.chen;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import org.chen.pool.JedisConnect;

import java.util.HashMap;

public class HashJedisTest {
  public static void main(String[] args) {
    JedisConnect connect = new JedisConnect();
    connect.execute(jedis -> {
      jedis.flushDB();

      //hash 类似于一个小redis,也是key/value这样存储的

      //存值
      jedis.hset("a1","name","girl");
      //取值
      System.out.println(jedis.hget("a1", "name"));//girl

      //jedis另一种存值
      HashMap<String, String> map = new HashMap<>();
      map.put("age","18");
      map.put("sex","baby");
      jedis.hset("a1", map);
      //批量取值
      System.out.println(jedis.hmget("a1", "name", "age", "sex"));//[girl, 18, baby]

      //批量存值
      HashMap<String, String> map2 = new HashMap<>();
      map2.put("name","boy");
      map2.put("age","28");
      map2.put("sex","1");
      jedis.hmset("a2",map2);
      System.out.println(jedis.hmget("a2", "name", "age", "sex"));//[boy, 28, 1]

      //从key中删除指定的field
      jedis.hdel("a1","sex");
      System.out.println(jedis.hmget("a1", "name", "age", "sex"));//[girl, 18, null]

      //类似setnx,set if not exists,如果不存在这个field，则存储，否则什么也不做
      jedis.hsetnx("a1","name","apple");
      System.out.println(jedis.hmget("a1", "name"));//[girl]
      jedis.hsetnx("a1","sex","xxx");
      System.out.println(jedis.hmget("a1",  "sex"));//[xxx]

      //返回key集合中的所有field
      System.out.println(jedis.hkeys("a1"));//[name, age, sex]

      //返回key集合中的所有field的value,仅仅返回value
      System.out.println(jedis.hvals("a1"));//[girl, 18, xxx]

      //返回key集合中的所有field和它的value
      System.out.println(jedis.hgetAll("a1"));//{name=girl, age=18, sex=xxx}

      //判断key中是否存在field,1:存在，0：不存在
      System.out.println(jedis.hexists("a1", "name"));//true
      System.out.println(jedis.hexists("a1", "height"));//false

      //按整数步长自增
      System.out.println(jedis.hincrBy("a1", "age", 10));//28

      //按浮点数步长自增
      System.out.println(jedis.hincrByFloat("a1", "age", 0.4));//28.4

      //key的长度
      System.out.println(jedis.hlen("a1"));//3

      //key中field的value的长度
      System.out.println(jedis.hstrlen("a1", "name"));//4

    });
  }
}
